// serialportwrapper.cpp
#include "serialportwrapper.h"

SerialPortWrapper::SerialPortWrapper(QObject *parent)
    : QObject(parent)
    , m_serial(new QSerialPort(this))
    , m_detectTimer(new QTimer(this))
{
    connect(m_serial, &QSerialPort::readyRead, this, &SerialPortWrapper::readData);

// 修改为兼容版本的错误处理连接
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
    connect(m_serial,
            QOverload<QSerialPort::SerialPortError>::of(&QSerialPort::errorOccurred),
            this,
            &SerialPortWrapper::handleError);
#else
    connect(m_serial,
            QOverload<QSerialPort::SerialPortError>::of(&QSerialPort::error),
            this,
            &SerialPortWrapper::handleError);
#endif

    connect(m_detectTimer, &QTimer::timeout, this, &SerialPortWrapper::checkAvailablePorts);
}

SerialPortWrapper::~SerialPortWrapper()
{
    closePort();
}

QList<QSerialPortInfo> SerialPortWrapper::availablePorts() const
{
    return QSerialPortInfo::availablePorts();
}

bool SerialPortWrapper::openPort(const QString &portName, const PortConfig &config)
{
    if (m_serial->isOpen()) {
        emit errorOccurred(tr("Port is already open"));
        return false;
    }

    m_serial->setPortName(portName);
    m_serial->setBaudRate(config.baudRate);
    m_serial->setDataBits(config.dataBits);
    m_serial->setParity(config.parity);
    m_serial->setStopBits(config.stopBits);
    m_serial->setFlowControl(config.flowControl);

    if (m_serial->open(QIODevice::ReadWrite)) {
        return true;
    }

    emit errorOccurred(m_serial->errorString());
    return false;
}

void SerialPortWrapper::closePort()
{
    if (m_serial->isOpen()) {
        m_serial->close();
    }
}

bool SerialPortWrapper::isOpen() const
{
    return m_serial->isOpen();
}

qint64 SerialPortWrapper::writeData(const QByteArray &data)
{
    if (!m_serial->isOpen()) {
        emit errorOccurred(tr("Port is not open"));
        return -1;
    }

    qint64 bytesWritten = m_serial->write(data);
    if (bytesWritten == -1) {
        emit errorOccurred(m_serial->errorString());
    }
    return bytesWritten;
}

void SerialPortWrapper::enableAutoDetect(bool enable, int interval)
{
    if (enable) {
        m_detectTimer->start(interval);
    } else {
        m_detectTimer->stop();
    }
}

void SerialPortWrapper::readData()
{
    QByteArray data = m_serial->readAll();
    if (!data.isEmpty()) {
        emit dataReceived(data);
    }
}

void SerialPortWrapper::handleError(QSerialPort::SerialPortError error)
{
    if (error != QSerialPort::NoError) {
        // 获取错误描述
        QString errorString = m_serial->errorString();
        emit errorOccurred(errorString);

        // 自动关闭端口
        if (error == QSerialPort::ResourceError || error == QSerialPort::PermissionError) {
            closePort();
        }
    }
}

void SerialPortWrapper::checkAvailablePorts()
{
    auto currentPorts = availablePorts();
    m_lastPortList = currentPorts;
    emit portsListUpdated();
}
